<template>
  <div class="app-container">
    <div class="filter-container">
      <el-radio-group v-model="listQuery.type" style="margin-left: 5px" class="filter-item" @change="getList">
        <el-radio-button label="new_user">1元现金充电券</el-radio-button>
        <el-radio-button label="recharge_receive">充值赠送充电券</el-radio-button>
      </el-radio-group>
      <el-cascader
          class="filter-item"
          v-model="selectParent" :options="distributorsList"
          :props="distributorsProps"
          placeholder="所属经销商"
          @change="getList"
          style="width: 15%;margin-left:10px" clearable filterable></el-cascader>

      <el-input
          class="filter-item"
          placeholder="输入关键字进行过滤"
          v-model="listQuery.keyword"
          style="width: 15%;margin-left: 5px"
      >
      </el-input>
      <el-radio-group v-model="listQuery.is_active" style="margin-left: 5px" class="filter-item" @change="getList">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button :label="1">正常</el-radio-button>
        <el-radio-button :label="0">禁用</el-radio-button>
      </el-radio-group>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"
                 style="margin-left: 10px"
      >
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        添加
      </el-button>
      <!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"-->
      <!--                 @click="handleDownload"-->
      <!--      >-->
      <!--        导出-->
      <!--      </el-button>-->
      <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        审核-->
      <!--      </el-checkbox>-->
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" min-width="30">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="60" align="center" label="经销商">
        <template slot-scope="scope">
          <el-link>{{ scope.row.distributor_name }}</el-link>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>
      <el-table-column min-width="60" align="center" label="类型">
        <template slot-scope="scope">
          <el-link type="success">{{ scope.row.type }}</el-link>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>
      <el-table-column min-width="60" align="center" label="开始时间">
        <template slot-scope="scope">
          <span>{{ scope.row.start_date }}</span>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>
      <el-table-column min-width="60" align="center" label="结束时间">
        <template slot-scope="scope">
          <span>{{ scope.row.end_date }}</span>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>
      <el-table-column min-width="40" align="center" label="抵扣金额">
        <template slot-scope="scope">
          <span>{{ scope.row.fee }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="40" align="center" label="发券数量" v-if="listQuery.type=='new_user'">
        <template slot-scope="scope">
          <span>{{ scope.row.quantity }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="50" align="center" label="有效期">
        <template slot-scope="scope">
          <span>{{ scope.row.days }}天</span>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>

      <el-table-column min-width="40" align="center" label="状态">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.is_active"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus($event,scope.row.id)"

          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column min-width="60" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="60" align="center" label="领取人数">
        <template slot-scope="scope">
          <span>{{ scope.row.record_count }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="60" align="center" label="领取记录">
        <template slot-scope="scope">
          <el-button type="primary" size="small" icon="el-icon-view" @click="handleShow(scope.row)">
          查看
          </el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="60">
        <template slot-scope="scope">
          <el-button type="primary" size="small" icon="el-icon-edit" circle @click="handleUpdate(scope.row)">
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" circle @click="del(scope.row.id)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />


    <el-drawer
        :title="now_table"
        :visible.sync="drawerTableVisible"
        direction="rtl"
    >
      <el-radio-group v-model="drawerListQuery.status" style="margin-left: 5px;margin-top:10px" class="filter-item" @change="getDrawerList">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button label="1">待使用</el-radio-button>
        <el-radio-button label="2">已使用</el-radio-button>
        <el-radio-button label="3">已过期</el-radio-button>
      </el-radio-group>

      <el-table v-loading="listLoading" :data="drawerList" border fit highlight-current-row style="width: 100%;margin-top:20px">
        <el-table-column align="center" label="ID" min-width="60">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="60" align="center" label="用户昵称">
          <template slot-scope="scope">
            <el-link>{{ scope.row.nickname }}</el-link>
            <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
          </template>
        </el-table-column>
        <el-table-column min-width="100" align="center" label="使用时间">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 2">{{ scope.row.used_at }}</span>
            <span v-else-if="scope.row.status == 1">待使用</span>
            <span v-else>已过期</span>
            <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
          </template>
        </el-table-column>
        <el-table-column min-width="100" align="center" label="过期时间">
          <template slot-scope="scope">
            <span>{{ scope.row.expires_at }}</span>
            <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
          </template>
        </el-table-column>
        <el-table-column min-width="100" align="center" label="领取时间">
          <template slot-scope="scope">
            <span>{{ scope.row.created_at }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="drawerTotal>0" :total="drawerTotal" :page.sync="drawerListQuery.page" :limit.sync="drawerListQuery.limit"
                  @pagination="getDrawerList"
      />
    </el-drawer>



    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="60%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
               style="width: 90%; margin-left:5%;"
      >
        <el-form-item label="活动类型">
          <el-radio-group v-model="temp.type">
            <el-radio-button label="1元现金充电券">1元现金充电券</el-radio-button>
            <el-radio-button label="充值赠送充电券">充值赠送充电券</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
              v-model="temp.start_date"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
              v-model="temp.end_date"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="抵扣金额">
          <el-input v-model="temp.fee"   style="width: 50%"/>
        </el-form-item>
        <el-form-item label="有效天数">
          <el-input v-model="temp.days"  style="width: 50%"/>
        </el-form-item>
        <el-form-item label="发券数量" v-if="temp.type == '1元现金充电券'">
          <el-input v-model="temp.quantity"  style="width: 50%"/>
        </el-form-item>
        <el-form-item label="所属经销商">
          <el-cascader v-model="temp.distributor_id" ref="cascaderDistributors" :options="distributorsList"
                       :props="distributorsProps"
                       placeholder="请选择经销商"
                       @change="handleDistributorsChange($event)"
                       style="width: 80%" clearable></el-cascader>
        </el-form-item>
        <el-form-item style="margin-bottom: 20px;" label="活动规则">
          <el-input v-model="temp.content" :rows="1" type="textarea" class="article-textarea" autosize
                    placeholder="请输入内容"
          />
          <!--          <span v-show="contentShortLength" style="margin-left:10px" class="word-counter">{{ contentShortLength }}字</span>-->
        </el-form-item>
        <el-form-item label="活动图片">
          <el-upload
              action="/api/upload/base_image"
              list-type="picture-card"
              :file-list="fileList"
              :on-success="handleSuccess"
              :auto-upload="true"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <el-image
                  :src="file.url"
                  fit="contain"
                  style="height:146px;max-width:334px"
              >
              </el-image>
              <span class="el-upload-list__item-actions">
        <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file,fileList)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="参与设备">
          <template>
            <el-transfer
                @change="changeDevice"
                :titles="['未参与[设备编号]', '已参与[设备编号]']"
                v-model="temp.devices"
                :props="{
                 key: 'id',
                 label: 'sn'
                 }"
                :data="devices">

            </el-transfer>
          </template>
        </el-form-item>
        <el-card  v-if="temp.type == '充值赠送充电券'" style="margin-bottom: 20px;margin-top: 20px">
          <el-divider>满赠规则</el-divider>
          <el-form-item
              v-for="(value, index) in temp.moneys"
              :label="'规则'"
              :key="index"
          >
            <el-row :gutter="10">
              <el-col :xs="8" :sm="8" :lg="9">
                满赠金额:<el-input v-model="index" style="float:left"></el-input>
              </el-col>
              <el-col :xs="8" :sm="8" :lg="9">
                发券数量:<el-input type="number" v-model="temp.moneys[index]" style="float: left"></el-input>
              </el-col>
              <el-col :xs="8" :sm="8" :lg="6"><el-button style="margin-top:20px" @click.prevent="removeMoney(index)">删除</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button @click="addMoney">新增</el-button>
          </el-form-item>
        </el-card>
        <el-form-item label="是否开启">
          <el-radio-group v-model="temp.is_active" size="small">
            <el-radio-button :label="1">是</el-radio-button>
            <el-radio-button :label="0">否</el-radio-button>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button @click="resetForm">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():createData()">
            提交
          </el-button>
        </center>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <el-image width="100%" :src="dialogImageUrl" alt="" fit="contain"></el-image>
    </el-dialog>
  </div>
</template>

<script>
import {getList, create, del, changeStatus, getRecordList} from '@/api/coupon'
import {all, getDevice} from '@/api/distributors'
import Pagination from '@/components/Pagination'
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'

export default {
  name: 'DistributorsCoupon',
  components: {Pagination, ImageCropper, PanThumb},
  computed: {
    // contentShortLength() {
    //   return this.temp.description.length
    // },
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      drawerTableVisible:false,
      now_table:'',
      drawerList:[],
      drawerTotal:0,
      drawerListQuery: {
        page: 1,
        limit: 10,
        coupon_id:'',
        status: ''
      },
      disabled: false,
      fileList: [],
      // chargeList:[],
      // chargeList1:[],
      imagecropperShow: false,
      imagecropperKey: 0,
      menus: [],
      roles: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: '',
        distributor_id: '',
        is_active: '',
        type: 'new_user'
      },
      selectAreas: '',
      selectParent: '',
      dialogImageUrl: '',
      dialogVisible: false,
      devices: [],
      temp: {
        id: undefined,
        distributor_id: '',
        type: '1元现金充电券',
        is_active: 1,
        start_date:'',
        end_date:'',
        fee:'',
        moneys:[],
        days:[],
        quantity:'',
        content:'',
        devices:[],
        images: [],
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      rules: {
        name: [{required: true, message: '经销商名称不能为空', trigger: 'blur'}],
        owner_name: [{required: true, message: '负责人不能为空', trigger: 'blur'}],
        phone: [{required: true, message: '负责人手机号不能为空', trigger: 'blur'}],
        customer_service_phone: [{required: true, message: '客服电话不能为空', trigger: 'blur'}],
        // password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      addr: [],
      lastId: '',
      distributorsList: [],
      nowDistributor: '',
      disOptions: [],
      cityProps: {
        value: 'code',   // 指定选项的 值 为选项对象的某个属性值
        label: 'name',   // 指定选项 标签 为选项对象的某个属性值
        children: 'children'    //指定选项的 子选项 为选项对象的某个属性值
      },
      colors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ],
      distributorsProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      selectCityProps: {
        value: 'code',   // 指定选项的 值 为选项对象的某个属性值
        label: 'name',   // 指定选项 标签 为选项对象的某个属性值
        children: 'children',    //指定选项的 子选项 为选项对象的某个属性值
        checkStrictly: true
      },
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getSelector()
  },
  methods: {
    resetMoney(formName) {

    },
    handleShow(coupon){
      this.drawerTableVisible = true
      this.drawerListQuery.coupon_id = coupon.id
      this.getDrawerList()
    },
    getDrawerList(){
      getRecordList(this.drawerListQuery).then(response => {
        this.drawerList = response.data.list
        this.drawerTotal = response.data.total
      })
    },
    removeMoney(index) {
      this.$delete(this.temp.moneys, index);
      // var index = this.temp.moneys.indexOf(item)
      // if (index !== -1) {
      //   this.temp.moneys.splice(index, 1)
      // }
    },
    addMoney() {
      if(Object.keys(this.temp.moneys).length > 0){
        const keys = Object.keys(this.temp.moneys);
        let maxKey = Math.max(...keys);
        this.$set(this.temp.moneys, [maxKey+1], 0);
      }else{
        this.$set(this.temp.moneys, "0", 0);
      }
    },
    getDevice(distributorId) {
      if (Array.isArray(distributorId)) {
        this.lastId = distributorId[distributorId.length - 1];
      } else {
        this.lastId = distributorId;
      }
      getDevice(this.lastId).then(response => {
        this.devices = response.data
      })
    },
    handleRemove(file, fileList) {
      const key = this.fileList.indexOf(file)
      this.fileList.splice(key, 1)
    },
    changeDevice(){
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess(file, fileList) {
      this.fileList.push(file.data)
    },
    changeStatus(val, id) {
      changeStatus(val, id).then(response => {
        this.$notify.success({
          title: '消息提示',
          message: response.msg,
          offset: 100
        })
        this.getList()
      })
    },
    getSelector() {
      all('all').then(response => {
        this.distributorsList = response.data
      })
    },
    increase() {
      this.temp.rate += 5;
      if (this.temp.rate > 100) {
        this.temp.rate = 100;
      }
    },
    decrease() {
      this.temp.rate -= 5;
      if (this.temp.rate < 0) {
        this.temp.rate = 0;
      }
    },
    handleAddrChange(e) {
      // 获取当前选中节点的数组
      let addrNode = this.$refs['cascaderAddr'].getCheckedNodes()[0]
      let addrText = addrNode.pathLabels
      this.temp.province_name = addrText[0]
      this.temp.city_name = addrText[1]
      this.temp.area_name = addrText[2]
    },
    handleDistributorsChange(e) {
      this.getDevice(e)
    },
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.temp.avatar = resData.url
    },
    close() {
      this.imagecropperShow = false
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    getList() {
      if (this.selectParent && this.selectParent.length > 0) {
        this.listQuery.distributor_id = JSON.stringify(this.selectParent)
      } else {
        this.listQuery.distributor_id = ''
      }
      // this.getCharge()
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    resetForm() {
      this.dialogFormVisible = false
      this.resetTemp()
    },
    handleCreate() {
      this.resetTemp()
      this.getSelector()
      // this.editCharge()
      this.fileList = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.images = this.fileList
          if (Array.isArray(this.temp.distributor_id)) {
            this.temp.distributor_id = this.temp.distributor_id[this.temp.distributor_id.length - 1];
          }
          create(this.temp).then(response => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            if (response.code == 200) {
              this.$notify.success({
                title: '成功',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.resetTemp()
              this.getList()
            } else {
              this.$notify.error({
                title: '失败',
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.getSelector()
      // this.editCharge('['+row.distributor_id+']')
      if (typeof row.images === 'string' && row.images) {
        this.fileList = JSON.parse(row.images)
      } else {
        this.fileList = row.images
      }
      if (this.fileList == null || !this.fileList) {
        this.fileList = []
      }
      this.getDevice(row.distributor_id)
      this.temp = Object.assign({}, row) // copy obj
      setTimeout(() => {
        if (typeof row.devices === 'string' && row.devices) {
          this.temp.devices = JSON.parse(row.devices)
        }else{
          this.temp.devices = row.devices
        }
        if (this.temp.devices == null || !this.temp.devices) {
          this.temp.devices = []
        }
        this.temp.devices= this.temp.devices.map(str => Number(str));
      }, 800);
      // this.temp.areas = [row.province_id+'',row.city_id+'',row.area_id+'']
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    del(id) {
      this.$confirm('确认要删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(id).then(response => {
          // this.list.unshift(this.temp)
          if (response.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
            this.getList()
          } else {
            this.$notify.error({
              title: '失败',
              message: response.msg,
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },
    resetTemp() {
      this.temp ={
        id: undefined,
        distributor_id: '',
        type: '1元现金充电券',
        is_active: 1,
        start_date:'',
        end_date:'',
        fee:'',
        moneys:{},
        days:0,
        quantity:'',
        content:'',
        devices:[],
        images: [],
      }
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
<style scoped>
.avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
}
</style>
<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
